﻿using Guoc.BigMall.Domain;
using Guoc.BigMall.Infrastructure.Extension;
using Guoc.BigMall.Infrastructure.Log;
using Guoc.BigMall.Web.Services;
using Guoc.BigMall.WebService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;

namespace Guoc.BigMall.Web.Controllers
{
    public class WechatController : Controller
    {
        ILogger _log;
        IUserContextService _userContextService;
        IWechatService _wechatService;
        IAuthenticateService _authenticateService;
        ISettings _settings;
        /// <summary>
        ///  微信公众号上配置的加密串
        /// </summary>
        string _token="023huijitong";
        public WechatController(ILogger log, IWechatService wechatService, IUserContextService userContextService, 
            IAuthenticateService authenticateService, ISettings settings)
        {
            this._log = log;
            _wechatService = wechatService;
            _userContextService = userContextService;
             this._authenticateService = authenticateService;
            _settings = settings;
        }

        /// <summary>
        ///  微信公众号接入验证
        /// </summary>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index(string signature, string timestamp, string nonce, string echostr)
        {
            if (CheckSignature(signature, timestamp, nonce, this._token))
            {
                this._log.Info("微信公众号接入成功!");
                return Content(echostr);
            }
            else
            {
                this._log.Info("微信公众号接入失败!");
                return Content("Error!");
            }
        }

        private bool CheckSignature(string signature, string timestamp, string nonce, string token)
        {
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            //tmpStr = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            //SHA1  加密
            tmpStr = tmpStr.EncryptSHA1();
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature)
            {
                return true;    
            }
            else
            {
                return false;
            }
        }


 
        /// <summary>
        ///  微信静默登陆
        /// </summary>
        /// <param name="code"> code 值</param>
        /// <param name="state">门店code</param>
        /// <returns></returns>
        public ActionResult Login(string code, string state)
        {
            _log.Info("beign wechat login:");
            _log.Info("code={0},state={1}",code,state);
            var storeCode = state;
             var result= _authenticateService.WechatLogin(code, storeCode);
           // var url = @"http://www.huijitong.top/#/login?token=" + result.Token;
           var url = string.Format("{0}/#/login?token={1}", _settings.GetValue(SettingKeys.System_Domain), result.Token);

            _log.Info("redirect:{0}", url);
            return Redirect(url);
        }

        
        public ActionResult GetCurrentUser()
        {
            var user = _userContextService.Current;
            return new JsonNetResult(ResultModel.Ok(user));
        }

        /// <summary>
        /// 获取静默授权的微信链接
        /// </summary>
        /// <param name="storeCode"></param>
        /// <param name="loginUrl">跳转到登陆页</param>
        /// <returns></returns>
        public ActionResult GetCodeUrl(string storeCode, string loginUrl)
        {
            // loginUrl = @"http://www.huijitong.top/api/wechat/login";
            loginUrl = string.Format("{0}/api/wechat/login", _settings.GetValue(SettingKeys.System_Domain));
            var result = _authenticateService.GetCodeUrl(storeCode, loginUrl);
            return new JsonNetResult(ResultModel.Ok(result));
        }

        /// <summary>
        ///  微信授权登陆
        /// </summary>
        /// <param name="code"></param>
        /// <param name="storeCode"></param>
        /// <returns></returns>
        public ActionResult LoginNeedAuthenticate(string code, string storeCode)
        {
            var result = _authenticateService.WechatLogin(code, storeCode);

            return new JsonNetResult(ResultModel.Ok(result));
        }


        public ActionResult GetNickNameAndHeadImg(string code)
        {

            return new JsonNetResult(ResultModel.Ok());
        }

        

        /// <summary>
        ///  准备分享获取参数
        /// </summary>
        /// <returns></returns>
        public ActionResult ReadyShare(string url, string storeCode)
        {
            _log.Info("request ReadyShare： url={0},storeCode={1}", url, storeCode);
            var result = _wechatService.BuildJsSdkConfig(url, storeCode);
            _log.Info("response ReadyShare： {0}", result.SerializeObject());
            return new JsonNetResult(ResultModel.Ok(result));
        }

    }
}